from datetime import datetime

from flask import current_app
from flask import g
from flask import request, jsonify

from ihome import constants, db
from ihome.models import House, Order, Area, HouseImage, Facility
from ihome.utils.commons import login_required
from ihome.utils.image_storage import storage_image
from ihome.utils.response_code import RET
from . import api
import time


@api.route('/areas')
def areas():
    try:
        areas=Area.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='获取城区信息失败')
    areas_list=[]
    for i in areas:
        areas_list.append(i.to_dict())


    return jsonify(errno=RET.OK, errmsg='获取成功',data=areas_list)


@api.route('/houses')
def house_list():
    # 获取所有的参数
    args = request.args
    area_id = args.get('aid', '')
    start_date_str = args.get('sd', '')
    end_date_str = args.get('ed', '')
    # booking(订单量), price-inc(低到高), price-des(高到低),
    sort_key = args.get('sk', 'new')
    page = args.get('p', '1')
    max=args.get('ma','')
    min=args.get('mi','i')
    start_date = None
    end_date=None
    # 日期转换
    if start_date_str:
        start_date=datetime.strptime(start_date_str, "%Y-%m-%d")
    if  not start_date_str:#如果没有起始时间就默认是今天
        t = time.localtime()
        begin_mon_date_str = '%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)
        start_date=datetime.strptime(begin_mon_date_str, "%Y-%m-%d")
    if end_date_str:
        end_date=datetime.strptime(end_date_str, "%Y-%m-%d")
    #如果结束时间小于起始时间
    if end_date and start_date:
        if end_date<start_date:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    #条件列表

    filter=[]
    if max and min :
        filter.append(House.price<=int(max))
        filter.append(House.price>=int(min))
    if area_id:
        filter.append(House.area_id==area_id)

    conflict_order = None
    #找出时间冲突的房子
    try:
        if end_date:
            conflict_order=Order.query.filter(Order.end_date >= start_date,Order.begin_date <= end_date).all()
        if not end_date:
            conflict_order=Order.query.filter(Order.end_date>=start_date).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库操作失败')
    #把冲突房子的id查出来加入到这个表
    house_id=[]
    if conflict_order:
        for i in conflict_order:
            house_id.append(i.id)
        filter.append(House.id.notin_(house_id))
    # 根据筛选条件进行排序
    if sort_key=='booking':
        house=House.query.filter(*filter).order_by(House.order_count.desc())
    elif sort_key=='price-inc':
        house=House.query.filter(*filter).order_by(House.price.asc())
    elif sort_key == 'price-des':
        house = House.query.filter(*filter).order_by(House.price.desc())
    else:
        house=House.query.filter(*filter).order_by(House.create_time.desc())

    paginate=house.paginate(int(page),constants.HOME_PAGE_MAX_HOUSES,False)
    house_p=paginate.items
    total_page=paginate.pages

    house_l=[]
    for i in house_p:
        house_l.append(i.to_basic_dict())

    data={
        'total_page':total_page,
        'houses':house_l
    }

    return jsonify(errno=RET.OK, errmsg='请求成功', data=data)

#首页轮播图
@api.route('/houses/index')
def house_index():
    try:
        house=House.query.order_by(House.order_count.desc()).limit(constants.HOME_PAGE_MAX_HOUSES).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库操作失败')

    house_list=[]
    for i in house:
        house_list.append(i.to_basic_dict())

    return jsonify(errno=RET.OK, errmsg='请求成功', data=house_list)

#发布房源
@api.route('/houses',methods=['POST'])
@login_required
def release_houses():

    user_id=g.user_id
    data_dict=request.json
    title = data_dict.get('title')
    price = data_dict.get('price')
    address = data_dict.get('address')
    area_id = data_dict.get('area_id')
    room_count = data_dict.get('room_count')
    acreage = data_dict.get('acreage')
    unit = data_dict.get('unit')
    capacity = data_dict.get('capacity')
    beds = data_dict.get('beds')
    deposit = data_dict.get('deposit')
    min_days = data_dict.get('min_days')
    max_days = data_dict.get('max_days')

    if not all([title, price, address, area_id, room_count, acreage, unit, capacity, beds, deposit, min_days, max_days]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数缺失')
    try:
        price=int(float(price)*100)
        deposit=int(float(deposit)*100)
    except Exception as e:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')


        # 设置数据到模型
    house = House()
    house.user_id = user_id
    house.area_id = area_id
    house.title = title
    house.price = price
    house.address = address
    house.room_count = room_count
    house.acreage = acreage
    house.unit = unit
    house.capacity = capacity
    house.beds = beds
    house.deposit = deposit
    house.min_days = min_days
    house.max_days = max_days

    facility = data_dict.get('facility')
    if facility:
        facilities = Facility.query.filter(Facility.id.in_(facility)).all()
        house.facilities = facilities

    try:
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据库操作失败')
    return jsonify(errno=RET.OK, errmsg='请求成功', data={'house_id':house.id})


#上传图片
@api.route('/houses/<int:house_id>/images', methods=['POST'])
def up_image(house_id):
    try:
        image_file=request.files.get('house_image').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='图片上传失败')
    if not image_file:
        return jsonify(errno=RET.PARAMERR, errmsg='未上传图片')

    try:
        house=House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库操作失败')

    if not house:
        return jsonify(errno=RET.NODATA, errmsg='未找到该房屋')

    try:
        image=storage_image(image_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片到七牛失败")

    house.index_image_url = image
    try:
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据库操作失败')

    house_image=HouseImage()
    house_image.house_id=house.id
    house_image.url=image
    try:
        db.session.add(house_image)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据库操作失败')

    image_url=constants.QINIU_DOMIN_PREFIX+image
    return jsonify(errno=RET.OK, errmsg='请求成功', data={'url':image_url})


@api.route('/user/houses')
@login_required
def my_houses():
    user_id=g.user_id
    try:
        houses=House.query.filter(House.user_id==user_id).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")
    houses_dict = []
    for house in houses:
        houses_dict.append(house.to_basic_dict())
    return jsonify(errno=RET.OK, errmsg="OK", data=houses_dict)